#include "pch.h"
#include "GIFHelper.h"



HRESULT ReadFloatMetadata(IWICMetadataQueryReader* reader, LPCWSTR metadataName, float &value)
{
	
	PROPVARIANT propValue;
	PropVariantInit(&propValue);

	ThrowIfFailed(reader->GetMetadataByName(metadataName, &propValue));

	ThrowIfFailed(propValue.vt == VT_UI2 ? S_OK : E_FAIL);
		
	value = static_cast<FLOAT>(propValue.uiVal);
		
	PropVariantClear(&propValue);
	return S_OK;
}

HRESULT ReadBoolMetadata(IWICMetadataQueryReader* reader, LPCWSTR metadataName, bool &value)
{
	PROPVARIANT propValue;
	PropVariantInit(&propValue);

	ThrowIfFailed(reader->GetMetadataByName(metadataName, &propValue));

	ThrowIfFailed(propValue.vt == VT_BOOL ? S_OK : E_FAIL);

	value = static_cast<bool>(propValue.boolVal);

	PropVariantClear(&propValue);

	return S_OK;
}

HRESULT ReadUIntegerMetadata(IWICMetadataQueryReader* reader, LPCWSTR metadataName, UINT &value)
{
	PROPVARIANT propValue;
	PropVariantInit(&propValue);

	ThrowIfFailed(reader->GetMetadataByName(metadataName, &propValue));

	ThrowIfFailed(propValue.vt == VT_UI2 ? S_OK : E_FAIL);

	value = static_cast<UINT>(propValue.uiVal);

	PropVariantClear(&propValue);
	return S_OK;
}

HRESULT ReadUCharMetadata(IWICMetadataQueryReader* reader, LPCWSTR metadataName, UINT &value)
{
	PROPVARIANT propValue;
	PropVariantInit(&propValue);

	ThrowIfFailed(reader->GetMetadataByName(metadataName, &propValue));

	ThrowIfFailed(propValue.vt == VT_UI1 ? S_OK : E_FAIL);

	value = propValue.bVal;

	PropVariantClear(&propValue);
	return S_OK;
}

IStream* createIStreamFromIBuffer(Streams::IBuffer ^buffer)  {
	// convert the IBuffer into an IStream to be used with WIC
	IStream *fileContentsStream;
	HRESULT res = CreateStreamOnHGlobal(NULL, TRUE, &fileContentsStream);

	if (FAILED(res) || !fileContentsStream) {
		return nullptr;
	}

	Streams::DataReader^ dataReader = Streams::DataReader::FromBuffer(buffer);

	// read the data into the stream in chunks of 1MB to preserve memory
	while (dataReader->UnconsumedBufferLength > 0) {

		UINT chunkSize = min(DL_BUFFER_SIZE, dataReader->UnconsumedBufferLength);
		auto data = ref new Platform::Array<uint8>(chunkSize);

		dataReader->ReadBytes(data);

		ULONG written;
		res = fileContentsStream->Write(data->Data, chunkSize, &written);

		if (FAILED(res) || written != chunkSize) {
			fileContentsStream->Release();

			return nullptr;
		}
	}

	return fileContentsStream;
}
